import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import HomeView from '../views/HomeView.vue'
import {getToken, removeToken } from '@/utils/auth.js'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: false }
  },
  {
    path: '/problems',
    name: 'problems',
    component: () => import('../views/ProblemsView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/problems/:id',
    name: 'problem-detail',
    component: () => import('../views/ProblemDetailView.vue'),
    props: true,
    meta: { requiresAuth: true }
  },
  {
    path: '/blogs',
    name: 'blogs',
    component: () => import('../views/BlogView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/blog',
    redirect: '/blogs'
  },
  {
    path: '/recruitment',
    name: 'recruitment',
    component: () => import('../views/RecruitmentView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/chat',
    name: 'chat',
    component: () => import('../views/ChatView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/blogs/:id',
    name: 'blog-detail',
    component: () => import('../views/BlogDetailView.vue'),
    props: true,
    meta: { requiresAuth: true }
  },
  {
    path: '/blogs/create',
    name: 'blog-create',
    component: () => import('../views/CreateBlogView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/RegisterView.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue')
  },
  {
    path: '/profile',
    name: 'profile',
    component: () => import('../views/ProfileView.vue'),
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  const isLoggedIn = !!getToken()
  
  try {
    // 处理token存在但store状态未初始化的情况（如直接URL访问）
    if (isLoggedIn && !userStore.isLoggedIn) {
      try {
        // 尝试使用token恢复用户状态
        await userStore.fetchUserStats()
        userStore.userStats.isLoggedIn = true
      } catch (error) {
        // token无效，清理并跳转到登录页
        removeToken()
        next({
          path: '/login',
          query: { expired: '1' }
        })
        return
      }
    }
    
    // // 确保已登录用户状态是最新的
    // if (userStore.isLoggedIn && isLoggedIn) {
    //   try {
    //     await userStore.fetchUserStats()
    //   } catch (error) {
    //     if (error.message.includes('身份信息已过期')) {
    //       // token过期时跳转到登录页并显示提示
    //       next({
    //         path: '/login',
    //         query: { expired: '1' }
    //       })
    //       return
    //     }
    //   }
    // }
    
    // 如果token不存在但store状态为已登录，清理store状态
    if (!isLoggedIn && userStore.isLoggedIn) {
      userStore.userStats.isLoggedIn = false
    }

    // 已登录用户禁止访问登录/注册页
    if (isLoggedIn && (to.name === 'login' || to.name === 'register')) {
      next('/')
      return
    }

    // 需要认证的页面
    if (to.meta.requiresAuth) {
      if (isLoggedIn) {
        next()
      } else {
        next({
          path: '/login',
          query: { redirect: to.fullPath }
        })
      }
    } else {
      next()
    }
  } catch (error) {
    console.error('路由守卫错误:', error)
    next('/')
  }
})

export default router
